package by.koleda.photoupdater.content;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import by.koleda.photoupdater.helpers.CommonAsyncTask;
import by.koleda.photoupdater.helpers.ParamCallback;

public abstract class ModelList<T> extends CommonAsyncTask<List<T>> {

	public static String TAG_RESPONSE = "response";
	
	public ModelList(ParamCallback<List<T>> paramCallback) {
		super(paramCallback);
	}

	@Override
	public List<T> convert(String source) throws Exception {
		if (source == null || source.length() == 0) {
			return null;
		}
		JSONObject jsonObject = new JSONObject(source);
		JSONArray array = jsonObject.getJSONArray(TAG_RESPONSE);
		if (array.length() == 0) {
			return null;
		}
		List<T> list = new ArrayList<T>();
		for (int i = 0; i < array.length(); i++) {
			list.add(createModel(array.getJSONObject(i)));
		}
		return list;
	}

	public abstract T createModel(JSONObject jsonObject) throws JSONException;

}
